package org.spider.util;

import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpUtils {

    public static Map<String, String> convertHeaders(Header[] headers){
        Map<String, String> results = new HashMap<>();
        for (Header header: headers) {
            results.put(header.getName(), header.getValue());
        }
        return results;
    }

    private static List<NameValuePair> getAllParams(Map<String,String> paramMap){
        List<NameValuePair> nameValuePairs = null;
        if (paramMap != null){
            nameValuePairs = new ArrayList<>();
            for (String paramKey:paramMap.keySet()){
                nameValuePairs.add(new BasicNameValuePair(paramKey,paramMap.get(paramKey)));
            }
        }
        return nameValuePairs;
    }

    private static String getResCookie(CloseableHttpResponse response){
        StringBuilder responseCookie = new StringBuilder();
        Header[] allHeader = response.getAllHeaders();
        if (allHeader != null) {
            for (Header header : allHeader) {
                if (header.getName().toLowerCase().contains("set-cookie")) {
                    String value = header.getValue();
                    if (!value.endsWith(";")) {
                        value = value + ";";
                    }
                    responseCookie.append(value);
                }
            }
        }
        return responseCookie.toString();
    }

    private static Map<String,String> getResHeaderMap(CloseableHttpResponse response){
        Map<String,String> headerMap = new HashMap<>();
        Header header = response.getFirstHeader("Content-Type");
        if (header != null){
            headerMap.put("Content-Type",header.getValue());
        }
        return headerMap;
    }
}
